import React, { useLayoutEffect, useReducer, useRef } from "react";

import ReactReduxContext from "../ReactReduxContext";
import shallowEqual from "./utils";

function useSelector(selector, equalityFn = shallowEqual) {
  const { store } = React.useContext(ReactReduxContext);
  const state = store.getState();

  // 用于优化
  const lastSelectedState = useRef(null);

  const selectedState = selector(state);

  const [, forceUpdate] = useReducer((x) => x + 1, 0);

  useLayoutEffect(() => {
    store.subscribe(() => {
      // 比较老状态和新选中状态是否相等，如果相等，不刷新
      const selectedState = selector(store.getState());
      // if (selectedState !== lastSelectedState.current) {
      if (!equalityFn(lastSelectedState.current, selectedState)) {
        forceUpdate();
        lastSelectedState.current = selectedState;
        console.log("重新渲染");
      }
      // forceUpdate();
    });
  }, []);
  return selectedState;
}

export default useSelector;
